package com.weatherapp.simple.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.weatherapp.simple.R;
import com.weatherapp.simple.model.City;
import java.util.List;

public class CityAdapter extends RecyclerView.Adapter<CityAdapter.ViewHolder> {
    
    private List<City> cityList;
    private OnCityClickListener listener;

    public interface OnCityClickListener {
        void onCityClick(City city);
        void onDeleteCity(City city, int position);
    }

    public CityAdapter(List<City> cityList) {
        this.cityList = cityList;
    }

    public void setOnCityClickListener(OnCityClickListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_city, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        City city = cityList.get(position);
        holder.tvCityName.setText(city.getName());
        holder.tvTemperature.setText(city.getCurrentTemperature() + "°C");
        holder.tvWeatherIcon.setText(city.getWeatherIcon());
        
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onCityClick(city);
            }
        });
        
        holder.itemView.setOnLongClickListener(v -> {
            if (listener != null) {
                listener.onDeleteCity(city, position);
            }
            return true;
        });
    }

    @Override
    public int getItemCount() {
        return cityList != null ? cityList.size() : 0;
    }

    public void updateData(List<City> newData) {
        this.cityList = newData;
        notifyDataSetChanged();
    }

    public void removeItem(int position) {
        if (position >= 0 && position < cityList.size()) {
            cityList.remove(position);
            notifyItemRemoved(position);
        }
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvCityName;
        TextView tvTemperature;
        TextView tvWeatherIcon;

        ViewHolder(View itemView) {
            super(itemView);
            tvCityName = itemView.findViewById(R.id.tv_city_name);
            tvTemperature = itemView.findViewById(R.id.tv_temperature);
            tvWeatherIcon = itemView.findViewById(R.id.tv_weather_icon);
        }
    }
}